<template>
  <view class="index-page pb-240rpx relative">
    <view class="sticky pos-top-0 z-1 bg-#fff pb-10rpx">
      <CircleTab :circleTabOptions="productTabOptions" @change="changeCircleTab"></CircleTab>
      <view class="flex ">
        <up-input shape="circle" class="mx-10pt text-44pt" placeholder="搜索产品名/中文描述/OEM编码/商家SKU编码" prefixIcon="search"
          prefixIconStyle="color: #909399" @change="(val) => searchProduct(val)"></up-input>
      </view>
    </view>
    <view v-for="(item, index) in productList" :key="index" class="index-page-card-box mx-24rpx"
      @click="gotoEdit(item)">
      <ProductCard :record="item"></ProductCard>
    </view>
    <view v-if="!productList.length" class="mt-168rpx w-320rpx m-auto  text-#999999">
      <img class="w-280rpx h-280rpx" :src="emptyImg">
      <view v-if="activeCircleTab === ' '">
        你还没有发布产品，点击“ <span class="font-size-38rpx">+</span> ”发布
      </view>
      <view class="text-center" v-else>
        暂无数据
      </view>
    </view>
  </view>
  <FloatingButton @operate="gotoProductList"></FloatingButton>
  <CustomTabbar page="productList"></CustomTabbar>
  <message-modal ref="msgRef" :delay="5" :auto="true" />
</template>

<script setup lang="ts">
import { productManageSupQueryProductSup, productManageSupQueryProductSupCount } from "@/genapi/productManageSup"
import { supplierQuerySupplierInfo } from "@/genapi/supplier"
import { tabOptions } from "@/utils/options";
import { debounce } from '@antfu/utils'
import emptyImg from "@/static/empty.png";
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

onLoad(() => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
})
onShareAppMessage(() => {
  return {
    title: '好达威供应商系统',
    path: '/pages/index/index',
  }
})
onShareTimeline(() => {
  return {
    title: '好达威供应商系统',
    path: '/pages/index/index',
  }
})

const productTabOptions = ref(tabOptions)
const activeCircleTab = ref(' ')
const productList = ref([])
const hasNext = ref<boolean>(true)
let apiParams: any = {
  page: 1,
  pageSize: 10,
}
function gotoProductList() {
  if (uni.getStorageSync('isNoLogin')) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return
  }
  uni.navigateTo({
    url: '/pages/createProduct/index'
  });
}
function gotoEdit(item: any) {
  let str = 'edit'
  if (item.productState === '0' || item.productState === '3') {
    str = 'create'
  }
  uni.navigateTo({
    url: `/pages/${str}Product/index?id=${item.id}`
  })
}
async function gotoLogin() {
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  if (isNoLogin) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return false
  } else {
    return true
  }

}
function search(val: string) {
  apiParams.searchText = val
  apiParams.page = 1
  productList.value.length = 0
  getProductList()
}
const searchProduct = debounce(500, search)

async function getProductList() {
  const isLogin = await gotoLogin()
  if (isLogin) {
    const { data } = await productManageSupQueryProductSup(apiParams)
    if (data?.code !== 200) return
    else {
      const result = data.data
      if (result.tableData)
        productList.value = productList.value.concat(result.tableData)
      productList.value = productList.value.map(item => {
        item.productPriceList.sort((a, b) => a.productPrice - b.productPrice)
        return item
      })
      if (result.totalElements) {
        if (activeCircleTab.value === '1') {
          productTabOptions.value[1].count = result.totalElements
        } else {
          productTabOptions.value[0].count = result.totalElements
        }
      }
      hasNext.value = result?.hasNext || false
    }
  }
}

// 下拉刷新
// onPullDownRefresh(async () => {
//   productList.value.length = 0
//   apiParams.page = 1
//   await getProductList()
//   uni.stopPullDownRefresh()
// })
// 上拉刷新
onReachBottom(() => {
  if (hasNext.value) {
    //页数累加
    apiParams.page++
    getProductList()
  }
})
// tab切换
const changeCircleTab = (val: string) => {
  activeCircleTab.value = val
  apiParams.productState = val
  apiParams.page = 1
  productList.value = []
  getProductList()
}
onShow(async () => {
  productList.value.length = 0
  apiParams.page = 1
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  if (isNoLogin) return
  getProductList()
})
async function getTabCount() {
  const { data } = await productManageSupQueryProductSupCount({})
  if (data?.code !== 200) return
  if (data.data?.length) {
    productTabOptions.value[1].count = 0
    data.data.map(item => {
      if (item.tabName !== '0' && item.tabName !== '3') {
        productTabOptions.value[1].count += +item.count
      }
    })
  }
}
onMounted(async () => {
  getTabCount()
  const { data } = await supplierQuerySupplierInfo({})
  if (data?.code !== 200) return
  else {
    uni.setNavigationBarTitle({
      title: data.data.supplierInfo.supplierName || '产品列表' // 页面标题为"自定义标题"
    });
  }
})
</script>

<style scoped>
.index-page {}
</style>
